package com.longjianghuasheng.logistics.business.inquiry

import android.os.Bundle
import android.widget.CompoundButton
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.fragment.app.setFragmentResultListener
import com.blankj.utilcode.util.TimeUtils
import com.longjianghuasheng.logistics.R
import com.longjianghuasheng.logistics.base.BaseTitleFragment
import com.longjianghuasheng.logistics.business.freight.ServiceListFragment.Companion.TYPE_DOMESTIC
import com.longjianghuasheng.logistics.business.freight.ServiceListFragment.Companion.TYPE_EXPORT
import com.longjianghuasheng.logistics.business.freight.ServiceListFragment.Companion.TYPE_IMPORT
import com.longjianghuasheng.logistics.business.home.TypeResponse
import com.longjianghuasheng.logistics.databinding.FragmentInquiryBinding
import com.longjianghuasheng.logistics.entity.AddressResponse
import com.longjianghuasheng.logistics.ext.observer
import com.longjianghuasheng.logistics.ext.showTimePicker
import com.longjianghuasheng.logistics.ext.toastNormal

class InquiryFragment : BaseTitleFragment<InquiryViewModel, FragmentInquiryBinding>() {
    override fun layoutId(): Int = R.layout.fragment_inquiry

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        mDatabind.initListener()

    }


    private fun FragmentInquiryBinding.initListener() {


        rgStart.setOnCheckedChangeListener { group, checkedId ->

            stvStart.isGone = checkedId == R.id.rb_start_huasheng
            mViewModel.start_type = if (checkedId == R.id.rb_start_huasheng) 1 else 2
        }

        stvStart.setRightImageViewClickListener {

            navigate(R.id.addressListFragment, Bundle().apply {
                putString("type", KEY_START_ADDRESS)
            })
        }

        stvEnd.setRightImageViewClickListener {

            navigate(R.id.addressListFragment, Bundle().apply {
                putString("type", KEY_END_ADDRESS)
            })
        }
        stvBonded.setOnClickListener {
            navigate(R.id.serviceSelectionFragment, Bundle().apply {
                putString("type", KEY_SERVICE1)
            })
        }
        stvAddition.setOnClickListener {
            navigate(R.id.serviceSelectionFragment, Bundle().apply {
                putString("type", KEY_SERVICE2)
            })
        }
        tvProtocol.setOnClickListener {
            navigate(R.id.aboutFragment, Bundle().apply {
                putInt("id", 1)
            })
        }

        rgPickUp.setOnCheckedChangeListener { group, checkedId ->

            mViewModel.type = if (checkedId == R.id.rb_container) 1 else 2

        }
        rgEnd.setOnCheckedChangeListener { group, checkedId ->
            mViewModel.end_type = if (checkedId == R.id.rb_end_huasheng) 1 else 2

            stvEnd.isGone = checkedId == R.id.rb_end_huasheng
        }


        rgWay.setOnCheckedChangeListener { group, checkedId ->
            val isOptional = checkedId == R.id.rb_optional
            tvModeOfTransportation.isVisible = isOptional
            rgModeOfTransportation.isVisible = isOptional

            if (!isOptional) {
                rbLandTransportation.isChecked = true
                rbSeaTransportation.isChecked = false
                rbRailwayTransport.isChecked = false
                rbService.isChecked = false
            }


        }

        rbLandTransportation.setOnCheckedChangeListener(::onCheckListener)
        rbSeaTransportation.setOnCheckedChangeListener(::onCheckListener)
        rbRailwayTransport.setOnCheckedChangeListener(::onCheckListener)
        rbService.setOnCheckedChangeListener(::onCheckListener)

        stvDate.setOnSuperTextViewClickListener {

            showTimePicker {

                mViewModel.sent_date = (TimeUtils.string2Millis(it, "yyyy-MM-dd") / 1000).toString()
                stvDate.setCenterString(it)
            }

        }

        btnImputedPrice.setOnClickListener {


            mViewModel.run {


                juli = stvDistance.centerEditValue

                sent_type = arrayMap.values.filterNot { it == 0 }.toMutableList()

                weights = stvWeight.centerEditValue

                ref_price()
            }
        }

        btnCommit.setOnClickListener {

            if (!cbConfirm.isChecked) {
                toastNormal("请勾选下面的协议")
                return@setOnClickListener
            }

            mViewModel.run {


                sent_type = arrayMap.values.filterNot { it == 0 }.toMutableList()

                start_address = stvStart.centerEditValue

                end_address = stvEnd.centerEditValue

                names = stvName.centerEditValue

                nums = stvNum.centerEditValue.ifBlank { "0" }.toInt()

                weights = stvWeight.centerEditValue

                volume = stvVolume.centerEditValue

                service_form()

            }

        }

    }

    private fun onCheckListener(buttonView: CompoundButton, isChecked: Boolean) {

        mViewModel.arrayMap.run {

            when (buttonView.id) {
                R.id.rb_land_transportation -> put(buttonView.id, if (isChecked) 1 else 0)
                R.id.rb_sea_transportation -> put(buttonView.id, if (isChecked) 2 else 0)
                R.id.rb_railway_transport -> put(buttonView.id, if (isChecked) 3 else 0)
                R.id.rb_service -> put(buttonView.id, if (isChecked) 4 else 0)
                else -> {}
            }
        }


    }


    override fun createObserver() {
        super.createObserver()
        mViewModel.result.observer(this) {
            navigateUp()
        }
        mViewModel.refPriceResult.observer(this) {
            mDatabind.stvReferencePrice.setCenterString(it.toString())
        }
        setFragmentResultListener(KEY_START_ADDRESS) { requestKey, bundle ->
            bundle.getParcelable<AddressResponse>("address")?.let {

                mViewModel.start_aid = it.id

                val address = it.province + it.city + it.area + it.address
                mDatabind.stvStart.setCenterEditString(address)
            }


        }
        setFragmentResultListener(KEY_END_ADDRESS) { requestKey, bundle ->
            bundle.getParcelable<AddressResponse>("address")?.let {
                mViewModel.end_aid = it.id

                val address = it.province + it.city + it.area + it.address

                mDatabind.stvEnd.setCenterEditString(address)
            }


        }
        setFragmentResultListener(KEY_SERVICE1) { requestKey, bundle ->

            bundle.getParcelableArray("service")?.map { it as TypeResponse }?.run {
                mViewModel.add_service1 = toList().joinToString(",") { it.id.toString() }
                mDatabind.stvBonded.setCenterString(
                    joinToString(",") { it.title ?: "" }
                )

            }

        }


        setFragmentResultListener(KEY_SERVICE2) { requestKey, bundle ->
            bundle.getParcelableArray("service")?.map { it as TypeResponse }?.run {


                mViewModel.add_service2 = toList().joinToString(",") {
                    it.id.toString()
                }
                mDatabind.stvAddition.setCenterString(
                    joinToString(",") { it.title ?: "" }
                )

            }
        }


    }

    override fun initData() {
        super.initData()
        arguments?.run {
            mViewModel.typeId = getInt(KEY_TYPE)
            mViewModel.service_id = getInt("id")
        }

        initTitleBar(
            when (mViewModel.typeId) {
                TYPE_IMPORT -> "进口询价"
                TYPE_EXPORT -> "出口询价"
                TYPE_DOMESTIC -> "国内运输"
                else -> ""
            }
        )

        mDatabind.init()
    }

    private fun FragmentInquiryBinding.init() {


        val isImportOrDomestic =
            mViewModel.typeId == TYPE_IMPORT || mViewModel.typeId == TYPE_DOMESTIC
        rgPickUp.isVisible = isImportOrDomestic


        rgStart.isVisible = mViewModel.typeId == TYPE_EXPORT



        stvStart.run {
            isGone = mViewModel.typeId == TYPE_EXPORT


        }
        mViewModel.start_type = if (mViewModel.typeId == TYPE_DOMESTIC) 2 else 1

        rgEnd.isVisible = isImportOrDomestic

        stvEnd.run {
            isGone = isImportOrDomestic
//            if (mViewModel.typeId != TYPE_IMPORT) {
//                setLeftString("目的地")
//                leftTextView.letterSpacing = 0.3F
//            }
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
    }

    companion object {
        const val KEY_TYPE = "type"
        const val KEY_START_ADDRESS = "start_address"
        const val KEY_END_ADDRESS = "end_address"
        const val KEY_SERVICE1 = "service1"
        const val KEY_SERVICE2 = "service2"
    }

}